package com.pi.config.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;

import com.pi.base.enumerate.record.RecordState;
import com.pi.base.util.text.PinyinTools;
import com.pi.base.util.text.TextEncodeUtil;
import com.pi.config.dao.entity.BaseNameIdxEntity;
import com.pi.config.dao.mapper.BaseNameIdxMapper;

/**
 * 小区服务
 * 
 * @author chenmfa
 * @date 2019年9月13日15:28:06
 */
@Validated
@Service
public class BaseNameIdxService {
    private BaseNameIdxMapper baseNameIdxMapper;
    
    @Autowired
    public BaseNameIdxService(BaseNameIdxMapper baseNameIdxMapper){
      Assert.notNull(baseNameIdxMapper, "名称索引服务为空");
      this.baseNameIdxMapper = baseNameIdxMapper;
    }
    
    public List<BaseNameIdxEntity> searchNameEntity(Integer idxType, String name){
      if(StringUtils.isBlank(name)){
        return Collections.emptyList();
      }
      List<String> nameKeyList;
      if(TextEncodeUtil.hasChinese(name)){
          nameKeyList = PinyinTools.getShortPingYin(name);
      }else{
          nameKeyList = new ArrayList<>(1);
          nameKeyList.add(name);
      }
      return baseNameIdxMapper.queryNameIdxByNameKey(idxType, nameKeyList);
    }
    
    public void addNameIndex(@NotNull(message = "索引来源不能为空") Long id,             
            @NotBlank(message="索引名称不能为空")
            @Length(max = 30) String name,
            @NotNull(message = "索引类型不能为空") Integer nameType){
        List<String> nameHashList = PinyinTools.getAlternativePinYin(name);
        List<BaseNameIdxEntity> list = new ArrayList<>(nameHashList.size());
        for(String nameHash : nameHashList){
            BaseNameIdxEntity entity = new BaseNameIdxEntity();
            entity.setNameCache(nameHash);
            entity.setNameId(id);
            entity.setNameType(nameType);
            entity.setState(RecordState.STATE_NORMAL.getState());
        }
        baseNameIdxMapper.batchInsert(list);
    }
}